#ifndef MAINWINDOW_H
#define MAINWINDOW_H

#include <QtGui>
#include <opencv/cv.h>
#include "imagedocument.h"
#include "ip.h"
#include "ocr.h"

class ImageLabel : public QLabel
{
  Q_OBJECT
public:
  QPoint m_point;
  double m_scale;
  ImageLabel(double scale = 1.0, QWidget* parent = 0)
    : QLabel(parent), m_point(0, 0), m_scale(scale)
  {}
signals:
  void mousePressed();
protected:
  void mousePressEvent(QMouseEvent* ev)
  {
    m_point = ev->pos();
    QTextStream(stdout) << m_point.x() << " " << m_point.y() << endl;
    emit mousePressed();
  }
  void mouseMoveEvent(QMouseEvent* ev)
  {
    m_point = ev->pos();
    QTextStream(stdout) << m_point.x() << " " << m_point.y() << endl;
    emit mousePressed();
  }
public:
  void show(const cv::Mat& mat) {
    cv::Mat big;
    cv::resize(mat, big, cv::Size(mat.size().width*m_scale, mat.size().height*m_scale));
    QImage m_image = IP::mat2qimage(big);
    //cv::Mat mat = IP::qimage2mat(m_image);
    //cv::imshow("show", mat);
    setPixmap(QPixmap::fromImage(m_image));
    adjustSize();
  }
};

class MainWindow : public QMainWindow
{
  Q_OBJECT
public:
  explicit MainWindow(QWidget *parent = 0);
  ~MainWindow();
signals:
  void curCharImageChanged();
  void curCharTextChanged();
  void imgChanged();
  void magnifyChanged();
public slots:
  void askAndLoad();
  void askAndLoadText();
  void loadCurrentSet();
  void showImage();
  void showMagnify();
  void showLine(int line);
  void selectionTextChanged();
  void showCharImgOnPressed();
  void showRegcognizedText();
  void lineDetected(int startLine, int endLine);
  void parseFinished();
  void moveText(int d);
  void moveImage(int d);
  void checkRecognizedText();
private:
  QScrollArea *m_scrollArea;
  ImageLabel *m_imgLabel, *m_charImgLabel, *m_magnifyLabel;
  QLabel *m_charTextLabel, *m_recognizedLabel;
  QTextEdit *m_origText;
  QToolBar *m_toolbar;
  QAction *m_loadImageAct, *m_loadTextAct, *m_loadCurrentSet;

  QImage m_image;
  cv::Mat m_mat, m_tmp;
  double m_scaleFactor;

  ImageDocument m_imgDoc;
  cv::Mat m_curCharImage;
  QString m_curCharText;

  OCR m_ocr;

  void createLayout();
  void createAction();
  void connectSignal();

  void keyPressEvent(QKeyEvent * ev );
};

#endif // MAINWINDOW_H
